package controller;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import pojo.Topic;
import pojo.User;

import java.util.*;

import dao.BookDAO;
import dao.TopicDAO;
import dao.UserDAO;
 
@Controller
public class DangNhapController {
	private String tenDangNhap;
	private String matKhau;
	private HttpServletRequest request;	
    @RequestMapping(value= "/DangNhap.do" , method = RequestMethod.GET)
    public String dangnhap(
			Model model,
			HttpServletRequest _request
    		) {
    	HttpSession session = _request.getSession();
    	User user= (User) session.getAttribute("user");
    	if(user!=null) return "redirect:/home";
    	else
        return ("page/FrontEnd/DangNhap");
    }
   
    @RequestMapping(value= "/DangNhap.do" , method = RequestMethod.POST)
    public String getsach(
    		@RequestParam(value="id", required = false) String id,
			@RequestParam(value ="password", required = false) String pass,
			Model model,
			HttpServletRequest _request
    		) {
		tenDangNhap = id;
		matKhau = pass;
		request = _request;
    	UserDAO ud= new UserDAO();
    	HttpSession session = request.getSession();
    	String oldUrl= (String) session.getAttribute("oldUrl");
    	String url="home";
    	if(oldUrl!=null) url=oldUrl;
    	int kq=ud.kiemTraDangNhap(tenDangNhap, matKhau);
    	synchronized (session) {
            if(kq==1)
            {

            	User us = ud.getUser(tenDangNhap);
				session.setAttribute("user", us);
            	model.addAttribute("output","Đăng nhập thành công");
            	if(us.getIsAdmin()==1) url="admin";
            	//model.addAttribute("link",url);
            	String redi="redirect:"+url;
            	return redi;
            }
            else
            {
            	model.addAttribute("output","Đăng nhập không thành công");
            	model.addAttribute("link","DangNhap.do");
            	return ("template/ketqua");
            }        
    	}

    }
   
}